package com.gosling.cloudspace.tools;

import cn.hutool.crypto.digest.MD5;

import java.util.LinkedList;

/**
 * 搜索关键词-排列组合算法
 *
 * @author wrx
 * @date 2022/10/11 16:47
 */
public class PermutCombinTool {

    /***
     * 相邻词语的组合
     *
     * @param keyWords
     * @return
     * @throws Exception
     */
    public static String permutAndCombin(String keyWords) throws Exception {
        char[] chars = keyWords.toCharArray();
        StringBuffer encript = new StringBuffer();
        StringBuffer field = new StringBuffer();
        LinkedList<String> linkedHashSet = new LinkedList<>();
        // 1.单个字加密组合
        for (char aChar : chars) {
            String value = String.valueOf(aChar);
            linkedHashSet.add(value);
            encript.append(MD5.create().digestHex16(value));
        }
        for (int i = 0; i < linkedHashSet.size(); i++) {
            for (int k = 0; k < linkedHashSet.size(); k++) {
                // field每次append(x+1)个字段,字段由首尾和中间的组成
                // 2.两个字组合加密
                if (Math.abs(k - i) == 1) {
                    field.append(linkedHashSet.get(i));
                    field.append(linkedHashSet.get(k));
                    encript.append(MD5.create().digestHex16(field.toString()));
                    field = new StringBuffer();
                    // 3.两字以上组合加密
                } else if (Math.abs(k - i) > 1) {
                    // 首位字 i>k i是尾,k是头
                    boolean flag = i > k;
                    if (flag) {
                        field.append(linkedHashSet.get(k));
                    } else {
                        continue;
                    }
                    //i: 0  1  2  3  4
                    //   凡 人 修 仙 转
                    //k: 0  1  2  3  4
                    //   凡 人 修 仙 转
                    // 中间的字数
                    int fileTargetCount = Math.abs(k - i) - 1;
                    int count = 1;
                    while (count <= fileTargetCount) {
                        if (flag) {
                            field.append(linkedHashSet.get(k + count));
                        }
                        count++;
                    }
                    // 尾字 i>k i是尾,k是头
                    if (flag) {
                        field.append(linkedHashSet.get(i));
                    } else {
                        field.append(linkedHashSet.get(k));
                    }
                    encript.append(MD5.create().digestHex16(field.toString()));
                    field = new StringBuffer();
                }
            }
        }
        return encript.toString();
    }
}
